package com.ckx.filter;

import com.alibaba.fastjson.JSON;
import com.ckx.constants.SystemConstants;
import com.ckx.domain.ResponseResult;
import com.ckx.domain.entity.LoginUserDetails;
import com.ckx.enums.AppHttpCodeEnum;
import com.ckx.utils.JwtUtil;
import com.ckx.utils.RedisCache;
import com.ckx.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * jwt校验过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取 token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //无携带 token放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析 token
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //token超时  token非法
            //响应告诉前端需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        String userId = claims.getSubject();

        //Redis获取 用户信息
        LoginUserDetails loginUser = redisCache.getCacheObject(SystemConstants.ADMIN_LOGIN + userId);
        if (Objects.isNull(loginUser)) {
            //说明登录过期  提示重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return;
        }
        //刷新过期时间
        redisCache.setCacheObject(SystemConstants.ADMIN_LOGIN + userId, loginUser,
                60, TimeUnit.MINUTES);
        //三参已认证
        //todo 权限传入(目前使用自定义集合存储)
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        //存入 SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request, response);
    }
}
